import { type Router, createRouter, createWebHashHistory } from 'vue-router'
import { Message } from '@/utils/message'
import NProgress from '@/utils/progress'
import { storageLocal } from '@/store/util'
import Home from './modules/home'
import remaining from './modules/remaining'
import { useUserStore } from '@/store/modules/user'
import { $t } from '@/plugins/i18n'
import { useMultiTagsStoreHook } from '@/store/modules/multiTags'
// import { handleAliveRoute } from './utils'
/** 自动导入全部静态路由，无需再手动引入！匹配 src/router/modules 目录（任何嵌套级别）中具有 .ts 扩展名的所有文件，除了 remaining.ts 文件
 * 如何匹配所有文件请看：https://github.com/mrmlnc/fast-glob#basic-syntax
 * 如何排除文件请看：https://cn.vitejs.dev/guide/features.html#negative-patterns
 */
//'!./modules/**/remaining.ts'
const modules: Record<string, any> = import.meta.glob(
  ['./modules/**/*.ts', '!./modules/**/home.ts'],
  {
    eager: true
  }
)

/** 原始静态路由（未做任何处理） */

export const routes = [remaining]
export const staticRoutes = [Home]

Home.children.push({
  path: '/noAuth',
  name: 'noAuth',
  component: () => import('@/views/error/403.vue'),
  meta: {
    title: $t('route.noAuth'),
    icon: 'icon-noAuth',
    menu: false,
    rank: 999,
    transparent: false
  }
})

Object.keys(modules).forEach(key => {
  if (modules[key].default.level)
    return Home.children.push(modules[key].default)

  staticRoutes.push(modules[key].default)
})

/** 创建路由实例 */
export const router: Router = createRouter({
  history: createWebHashHistory(),
  routes: staticRoutes,
  strict: true,
  scrollBehavior(to, from, savedPosition) {
    return new Promise(resolve => {
      if (savedPosition) {
        return savedPosition
      } else {
        if (from.meta.saveSrollTop) {
          const top: number =
            document.documentElement.scrollTop || document.body.scrollTop
          resolve({ left: 0, top })
        }
      }
    })
  }
})

router.beforeEach(async (to, _from, next) => {
  const accessToken = storageLocal().getItem('accessToken')
  NProgress.start()

  if (to.path !== '/login') {
    if (!accessToken) {
      next('/login')
    } else {
      try {
        const userStore = useUserStore()
        if (userStore.userAuth === null) await userStore.checkUserInfo()
        if (
          userStore.userInfo.roleCode === 'Administrator' ||
          userStore.menuAuth.has(to.name as string) ||
          to.path === '/noAuth'
        ) {
          next()
          useMultiTagsStoreHook().handleTags('push', to)
        } else {
          next('/noAuth?redirect=' + to.path)
        }
      } catch (err) {
        Message.error(err)
      }
    }
  } else {
    next()
  }
})

router.afterEach(() => {
  NProgress.done()
})

export default router
